#include <WiFi.h>

const char* ssid = "sync_ap";
const char* password = "zxcv123456";
const char* host = "192.168.4.1";  // AP的默认IP
const int port = 1234;

bool syncCompleted = false;
unsigned long startTime = 0;
int syncTimeout = 70000;    // 15秒同步超时
int autoStartDelay = 4000;  // 20秒后自动启动

#define RL 9
#define RH 8
#define RP 7
#define LL 6
#define LH 5
#define LP 4




void setup() {
  //串口
  Serial.begin(115200);
  delay(1000);
  pinMode(RL, OUTPUT);
  pinMode(RH, OUTPUT);
  pinMode(LL, OUTPUT);
  pinMode(LH, OUTPUT);

  // 初始状态设为停止
  stopAll();

  WiFi.begin(ssid, password);
  Serial.print("Connecting to AP");
  unsigned long connectStartTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - connectStartTime < 60000) {
    Serial.println((syncTimeout - (millis() - connectStartTime)) / 1000);
    delay(500);
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\nConnected to AP");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    // 尝试同步
    attemptSync();
  } else {
    Serial.println("\nFailed to connect to AP");
  }
}

void r_clockTurn(int p) {
  digitalWrite(RL, HIGH);
  digitalWrite(RH, LOW);
  analogWrite(RP, p);
}

void l_clockTurn(int p) {
  digitalWrite(LL, HIGH);
  digitalWrite(LH, LOW);
  analogWrite(LP, p);
}

void r_unclockTurn(int p) {
  digitalWrite(RL, LOW);
  digitalWrite(RH, HIGH);
  analogWrite(RP, p);
}

void l_unclockTurn(int p) {
  digitalWrite(LL, LOW);
  digitalWrite(LH, HIGH);
  analogWrite(LP, p);
}

void stopAll() {
  digitalWrite(RL, LOW);
  digitalWrite(RH, LOW);
  digitalWrite(LL, LOW);
  digitalWrite(LH, LOW);
}

void loop() {
  if ((millis() - startTime) % 1000 == 0) Serial.println((millis() - startTime) / 1000);

  // 检查同步超时
  if (!syncCompleted && millis() - startTime > syncTimeout) {
    Serial.println("Sync timeout, waiting for auto start...");
    syncCompleted = true;  // 防止重复进入
    startProgram();
  }
  attemptSync();
  // 检查是否已经同步
  if (syncCompleted) {
    // 程序已在attemptSync中启动
    return;
  }
}

void attemptSync() {
  Serial.print("Connecting to server: ");
  Serial.println(host);

  WiFiClient client;
  if (!client.connect(host, port)) {
    Serial.println("Connection to server failed");
    return;
  }

  Serial.println("Connected to server, sending sync request");
  client.println("SYNC_REQUEST");

  // 等待响应
  unsigned long sendTime = millis();
  while (client.connected() && millis() - startTime < syncTimeout) {
    if (client.available()) {
      String response = client.readStringUntil('\n');
      response.trim();

      if (response == "SYNC_ACK") {
        Serial.println("Sync acknowledged");
        syncCompleted = true;
        Serial.println("Sync completed, starting program...");
        startProgram();
        break;
      }
    }
    delay(10);
  }

  client.stop();
}
void wait(int t) {
  for (int i = 0; i < t + 1; i++) {
    if (i % 1000 == 0) Serial.println(t - i);
    delay(1);
  }
}
void startProgram() {
  Serial.print(millis());
  Serial.println("Program started on STA device!");
  while (true) {
    // 主程序循环
    int p = 150;
    l_clockTurn(p);
    Serial.println("右顺时针旋转");
    wait(63000);
    stopAll();
    wait(1000);
    l_unclockTurn(p);
    Serial.println("右逆时针旋转");
    wait(63000);
    stopAll();
    wait(1000);
  }
}